const path = require('path')
const fs = require('fs-extra-promise')
const axios = require('axios')
const mkdirp = require('mkdirp')

const mirrorData = require('./mirror.json')

const downloadUrlPrefix = 'https://github.com/zhangyuanwei/node-images/releases/download/'

async function main() {
  console.log(`Starting download node-images-bindings ...`)
  for (const vData of mirrorData.versions) {
    console.log(`Version ${vData.version}: `)
    const versionDir = path.resolve(__dirname, `./v${vData.version}`)

    if (!(await fs.existsAsync(versionDir))) {
      console.log(`Version dir '${versionDir}' does not exist, creating ...`)
      await new Promise((resolve, reject) => {
        mkdirp(versionDir, (err) => {
          if (err) return reject(err)
          resolve()
        })
      })
      console.log(`Version dir ${versionDir} created.`)
    }

    for (const file of vData.files) {
      const fullUrl = downloadUrlPrefix + [`v${vData.version}`, file].join('/')
      const fullPath = path.join(versionDir, file)

      if (await fs.existsAsync(fullPath)) {
        console.log(`File ${fullPath} exist, skip download ...`)
        continue
      }

      console.log(`File ${fullUrl} downloading ...`)
      const writeStream = fs.createWriteStream(fullPath)
      await axios({
        method: 'get',
        url: fullUrl,
        responseType: 'stream'
      }).then(function (response) {
        return new Promise((resolve, reject) => {
          response.data.pipe(writeStream)

          writeStream.on('error', (err) => {
            reject(err)
          })

          writeStream.on('finish', () => {
            resolve()
          })
        })
      })
      console.log(`File ${fullUrl} done...`)
    }
  }
}

main()
  .then(() => console.log('download done.'))
  .catch(console.error)